CommonUtils.regNamespace("com.im.countPay");
com.im.countPay.invoke = function() {
	var param = {
		pageNumber: 1,
	    pageSize: 20
	};
    var client = new com.im.common.ajax();
    var operType = "";
    var countPay;
    function _init() {
        //加载列表信息
    	_initDataList();
    	//重置按钮
    	$('#ResetBtn').click(function (){
    		_resetSearchInfo();
    	});
        //查询按钮
        $("#SearchBtn").click(function(){
        	_loadDataList();
        });
        //所属规划-建设单位-实施项目
        $("#searchPlanProjClass").project2unit2itemCommpent({
            elmIdPlanTypeSel : "searchPlanProjClass",
            elmIdUnitSel : "searchOrgName",//组织单位下拉元素
            elmIdItemSel : "searchImpleProjName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            	_loadDataList();
            }
        });
        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();
    };
    //重置搜索条件
    function _resetSearchInfo(){
    	$('#searchOrgName').val("").trigger("change");
    	$('#searchPlanProjClass').val("").trigger("change");
    	$('#searchImpleProjName').val("").trigger("change");
    }
    //更新数据列表
    function _loadDataList(){
    	param.pageNumber = 1;
    	var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	var orgId = $("#searchOrgName option:selected").attr("value");
    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
        param.impleProjId = impleProjId;
        param.orgId = orgId;
        param.planProjClass = planProjClass;
//    	var impleProjName = $("#searchImpleProjName").val();
//    	var contractCode = $("#searchContractCode").val();
//    	var contractName = $("#searchContractName").val();
//        param.impleProjName = impleProjName;
//        if(contractCode == ''){
//        	delete param.contractCode;
//        }else{
//        	param.contractCode = contractCode;
//        }
//        param.contractName = contractName;
      $('#countPayList').datagrid("load",param);
    }
    //保存操作
    function _getRowIndex(target){
		var tr = $(target).closest('tr.datagrid-row');
		return parseInt(tr.attr('datagrid-row-index'));
	}
    function _save(index,target){
    	com.im.common.confirm("确定要保存吗？", null, function () {
	    	$('#countPayList').datagrid('endEdit', _getRowIndex(target));
	    	$(target).hide().prev().show();
	    	$(target).next().hide();
	    	countPay = $('#countPayList').datagrid('getData').rows[index];
		    var saveparam={
		    	declareId : countPay.declareId,
		    	payId : countPay.payId,
		    	payCode : countPay.payCode,
		    	contractClauseId : countPay.contractClauseId,
		    	liablePerson : countPay.liablePerson,
		    	payDt : countPay.payDt,
		    	description : countPay.description
		    };
		    var result = client.callAsJson("metePayService/updateMetePay", saveparam);
		    if(result.resultCode=='0'){
		    	_loadDataList();
		    	mergeCellsByField('countPayList','contractName',"impleProjName,contractClauseName,meteDeclareTotal,declarer,declarerDt,payCode,liablePerson,payDt,description,operation");
		    	toastr.success("保存成功");
		    }else {
		    	mergeCellsByField('countPayList','contractName',"impleProjName,contractClauseName,meteDeclareTotal,declarer,declarerDt,payCode,liablePerson,payDt,description,operation");
		        toastr.error('请稍后再试！'+result.resultMsg);
		    }
    	});
    }
    //取消操作
    function _cancel(target){
    	$('#countPayList').datagrid('cancelEdit', _getRowIndex(target));
    	mergeCellsByField('countPayList','contractName',"impleProjName,contractClauseName,meteDeclareTotal,declarer,declarerDt,payCode,liablePerson,payDt,description,operation");
    }
    //编辑操作
    function _edit(target){
    	$('#countPayList').datagrid('beginEdit', _getRowIndex(target));
    	$(target).hide().next().show();
    	$(target).next().next().show();
        $('td[field="payDt"] .datagrid-editable-input').datepicker();
        $('td[field="liablePerson"] .datagrid-editable-input').each(function (index,element){
        	$(this).click(function() {
        		var _this = this;
    	        $(this).userSearchCommpent({
    	            elmIdOut : '',//组织树单击之后回填的文本框（input）
    	            elmIdModal : "userSearchModal",//用户选择
    	            elmIdOrgModal : "unitSearchModal1",//组织查询
    	            callbackFunc: function (staffId, staffName, mobilePhone) {//组织树单击之后回调函数
    	            	$('td[field="liablePerson"] .datagrid-editable-input:eq('+index+')').val(staffName).attr('statusCdId',staffId);
    	            }
    	        });
            });
        }); 
    }
    //合并单元格
    function mergeCellsByField(tableID, fldList,other) {
    	var Arr = fldList.split(",");  
        var dg = $('#' + tableID);  
        var fldName;  
        var RowCount = dg.datagrid("getRows").length;  
        var span;  
        var PerValue = "";  
        var CurValue = "";  
        var length = Arr.length - 1;  
        for (i = length; i >= 0; i--) {  
            fldName = Arr[i];  
            PerValue = "";  
            span = 1;  
            for (row = 0; row <= RowCount; row++) {  
                if (row == RowCount) {  
                    CurValue = "";  
                }  
                else {  
                    CurValue = dg.datagrid("getRows")[row][fldName];  
                } 
                if (PerValue === CurValue) {  
                    span += 1;  
                }  
                else {  
                    var index = row - span;  
                    dg.datagrid('mergeCells', {  
                        index: index,  
                        field: fldName,  
                        rowspan: span,  
                        colspan: null  
                    });  
                    var name = other.split(","); 
                    $.each(name,function (i,item){
                    	dg.datagrid('mergeCells', {  
                            index: index,  
                            field: item,  
                            rowspan: span,  
                            colspan: null  
                        });
                    });
                    span = 1;  
                    PerValue = CurValue;  
                }  
            }  
        }  
    }

    //初始化表格数据
    function _initDataList(){
    	var columns=[[
    		{field:'index',title:"序号",width:50,resizable:true,
              	formatter: function(value,row,index){
                      return  index+1;
                  }
		    },
		    {field:'impleProjName',title:"实施项目名称",width:150,resizable:true},
		    //{field:'contractCode',title:"合同编号",width:150,resizable:true},
		    {field:'contractName',title:"合同名称",width:100,resizable:true},
		    //{field:'contractType',title:"合同类型",width:100,resizable:true},
    	    {field:'contractClauseName',title:"支付条款",width:120,resizable:true,align:'center'},
		    {field:'meteDeclareTotal',title:"总金额<br/>（万元）",resizable:true},
		    {field:'contractItemName',title:"合同分项",width:100,resizable:true},
		    {field:'amonut',title:"数量",width:80,resizable:true},
		    {field:'itemTotal',title:"金额<br/>（万元）",resizable:true},
		    {field:'payment',title:"支付金额<br/>（万元）",resizable:true},
		    {field:'paymentRatio',title:"支付比例",width:80,resizable:true},
		    {field:'declarer',title:"申请人",width:100,resizable:true},
		    {field:'declarerDt',title:"申请时间",width:100,resizable:true},
		    {field:'payCode',title:"支付编码",width:100,editor:'text',resizable:true},
		    {field:'liablePerson',title:"支付责任人",width:90,editor:'text',resizable:true},
		    {field:'payDt',title:"支付时间",width:100,editor:'text',resizable:true},
		    {field:'description',title:"备注",width:120,editor:'text',resizable:true},
		    {field:'operation',title:"操作",width:80,resizable:true,
		        formatter: function(value,row,index){
		        	return	'<a href="javascript:; "onclick="com.im.countPay.invoke.editList(this)" title="修改"><i class="fa fa-edit"></i></a>'+
	        				'<a href="javascript:; "onclick="com.im.countPay.invoke.saveList('+index+',this)" title="保存" style="display:none;"><i class="fa fa-check-square-o"></i></a>'+
	        				'<a href="javascript:; "onclick="com.im.countPay.invoke.cancelList(this)" title="取消" style="display:none;"><i class="fa fa-refresh"></i></a>';
		    }},
    	    
    	]];
    	$('#countPayList').datagrid({
    	    url:'/InfoManageWeb/metePayService/queryMetePayList',
    	    method:'post',
    	    dataType : 'json',
    	    queryParams:param,
    	    nowrap:false,
    	    fitColumns:true,
    	    pagination:true,
    	    columns:columns,
    	    loadMsg:'数据加载中，请耐心等待',
    	    onBeforeLoad : function(param){
	    	    for (var key in param) {
		    	    if(key=="rows"){
		    	    	delete param[key];
		    	    }
		    	}
    	    },
    	    loadFilter:function(data){
    	      if(data.resultCode!=0){
    	        toastr.error(data.resultCode);
    	        return null;
    	      }else{
    	        return data.result;
    	      }
    	    },
    	    onLoadSuccess: function (data) {
                if (data.rows.length > 0) {
                	mergeCellsByField('countPayList','contractName',"impleProjName,contractClauseName,meteDeclareTotal,declarer,declarerDt,payCode,liablePerson,payDt,description,operation");
                }
            }
    	});
    	var p = $('#countPayList').datagrid('getPager');
    	  $(p).pagination({
    	    pageSize: 20,
    	    pageList: [10,20,30],
    	    beforePageText: '第',
    	    afterPageText: '页    共 {pages}  页',
    	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    	    onSelectPage:function(pageNumber, pageSize){
    	      param.pageNumber=pageNumber;
    	      param.pageSize=pageSize;
    	      	var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	    	var orgId = $("#searchOrgName option:selected").attr("value");
    	    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
    	        param.impleProjId = impleProjId;
    	        param.orgId = orgId;
    	        param.planProjClass = planProjClass;
    	      $('#countPayList').datagrid('reload',param);
    	    }
    	  });
    }

	return {
		init : _init,
		cancelList : _cancel,
		editList : _edit,
		saveList : _save
	}
}();

$(function() {
	com.im.countPay.invoke.init();
});